package com.qnkf.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 商圈数据库
 */
@Configuration
@MapperScan(basePackages = "one.stand.managemapper", sqlSessionFactoryRef =  "manageSqlSessionFactory")
public class ManageDataSource {

    @Bean(name = "manageMainDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.manage.druid")

    public DataSource manageDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "manageSqlSessionFactory")
    public SqlSessionFactory manageSqlSessionFactory(@Qualifier("manageMainDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //读取mybatis小配置文件
        System.out.println("加载manageSqlSessionFactory");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:managemapping/*.xml"));
        //开启驼峰命名
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        bean.getObject().getConfiguration().setObjectWrapperFactory(new MybatisMapWrapperFactory());
        return bean.getObject();
    }

    @Bean(name = "manageTransactionManager")
    public DataSourceTransactionManager ymsqTransactionManager(@Qualifier("manageMainDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "manageSqlSessionTemplate")
    public SqlSessionTemplate manageSqlSessionTemplate(@Qualifier("manageSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
